<?php

// Europa100AD
//
// OOP Classes: User - Aug 2007 (K. Dougans)
//
// 
//

class user
{

  function __construct($user_id = 0) {
       //DEBUG print "In constructor\n";
       $this->user_id = $user_id;
   }
   

   function __destruct() {
     //  print "Destroying " . $this->name . "\n";
   }
   
   
    function email_verify($email) {
    // First, we check that there's one @ symbol, and that the lengths are right
        if (@!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) {
            // Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
            return false;
        }
        
        // Split it into sections to make life easier
        $email_array = explode("@", $email);
        $local_array = explode(".", $email_array[0]);
        for ($i = 0; $i < sizeof($local_array); $i++) {
            if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i])) {
                 return false;
            }
        }
        if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name
            $domain_array = explode(".", $email_array[1]);
            if (sizeof($domain_array) < 2) {
                return false; // Not enough parts to domain
            }
            for ($i = 0; $i < sizeof($domain_array); $i++) {
                if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])) {
                    return false;
                }
            }
        }
        return $email;
    }
    
    function random_string($length = 8) {
        # Set the characters we can use for the UID (must be HTTP friendly)
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789_ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        mt_srand((double)microtime()*1000000);
        $i = 1;
        $pass = '' ;
        
        while ($i <= $length) {
            $num = mt_rand() % strlen($chars);
            $tmp = substr($chars, $num, 1);
            $pass = $pass . $tmp;
            $i++;
        }
        
        return $pass;
    
    }
    
    function logout($user_id, $uid) {
        global $db;

        $sql = "DELETE FROM user_active WHERE `uid`='$uid' OR `assoc_id`='$user_id'";
        $db->query($sql);
    
    }
    
    function login($email,$password) {
        global $db, $config;
        
        $sql = "SELECT * FROM user_auth WHERE `email`='$email' AND `password`='$password' LIMIT 1";

        // run the query, returns result object
        $res = $db->query($sql);
        
        $row = $res->fetch_assoc();
        if ($row['id'] > 0)
        {
            //printf ("%s (%s)\n", $row["id"], $row["email"]);
            $login = $db->prepare("INSERT INTO user_active VALUES (?, ?, ?, ?, ?, ?)");
            $login->bind_param('sissss', $uid, $id, $ip_adr, $last_active, $current_page, $login_time);
            
            $uid = $this->random_string($config['uid_length']); // random string of 8 characters
            $id = $row['id'];
            $ip_adr = $_SERVER['REMOTE_ADDR'];;
            $current_page = 'login';
            $now = mktime();
            $last_active = $now;
            $login_time = $now;
            
            # Make sure there is no entries in the user_active database with this users id 
            $this->logout($row['id'], 0);
            
            # Add the new record in to user_active, prepared above
            $login->execute(); 
            return $uid;
        }
        else
        {
            echo '<b><font color=red>Incorrect Login details...</font></b>';
            return false;
        }
        
        
    }

 
function uid_check($uid) {
    global $db, $config, $user_id;
    
    $sql = "SELECT * FROM `user_active` WHERE `uid`='$uid'";

    // run the query, returns result object
    $res = $db->query($sql);
    
    $row = $res->fetch_assoc();
    $user_id = $row['assoc_id'];
    define('USER_ID',$user_id);
    if ($user_id > 0)
    {
        # UID is ok
        //$user_info[$user_id]['user_active'] = $row;
        return $row['uid'];
    }
    else
    {
        # UID couldn't be found in user_active
        $login_url = $config['url']['login'];
        //header("Location: $login_url");
        exit;
        return false;
    }  
}

function effort_check($effort_required,$effort_got) {
    global $db, $config, $user_id,$uid;
    
    if ($effort_got > $effort_required)
    {
        $sql = "UPDATE `user_stats` SET `effort`=effort-'$effort_required' WHERE `assoc_id`='$user_id'";
        $db->query($sql);
        return true;
    }
    else
    {
        # player needs effort
        $page_wanted = $_SERVER['REQUEST_URI'];
        $sql = "UPDATE `user_settings` SET `page_before_effort`='$page_wanted' WHERE `assoc_id`='$user_id'";
        $db->query($sql);
        $effort_url = $config['url']['play'] . $uid .'/effort/get/1/';
        header("Location: $effort_url");
        exit;
        return false;
    }  
}


 function load_tables($tables, $other = 0){
    global $db, $config;
    
    $user_id = $this->user_id;
    
    $tables = explode(",", $tables);
    
    // Other should be set to 1 if player information of another person is being loaded (not the logged in users information)
    if ($other == 1) { $table = 'user_settings'; } else { $table = 'user_active'; }
    
    $sql = "SELECT * FROM `$table`";
    
    foreach ($tables as $key => $value) {
        $sql .= " INNER JOIN $value ON $table.assoc_id = $value.assoc_id";
    }
    $sql .= " WHERE `$table`.`assoc_id`='$user_id'";
    
    //echo $sql;
    $res = $db->query($sql);
    
    return $res->fetch_assoc();
    
 }
 
# A function to handle and standardise items being given to users
#  by updating a db record if the user already has the item
#  or by adding a new db record if the user doesn't have the item
function get_item($item,$quantity,$exp = 0){
    global $db, $config;
    
    $user_id = $this->user_id;
    
    $sql = "SELECT * FROM `user_items` WHERE `assoc_id`='$user_id' AND `item`='$item'";
    if($res = $db->query($sql))
    {
        $num_rows = $res->num_rows;
        if ($num_rows > 0 && $exp == 0)
        {
            $sql = "UPDATE `user_items` SET `quantity` = quantity+'$quantity' WHERE `assoc_id` = '$user_id' AND `item`='$item' LIMIT 1";
            return $db->query($sql);
        }
        else
        {
            $sql = "INSERT INTO `user_items` (`assoc_id`, `item`, `quantity`,`exp`) VALUES ('$user_id','$item','$quantity','$exp')";
            return $db->query($sql);
        }
    }    
 }

function display_id(){
    $user_id = $this->user_id; //test
    return $user_id;
}

function display_info($user_info)
{
    $username = $user_info['prefix'] . '' . $user_info['username'] . '' . $user_info['postfix'];
    $user_id = $user_info['assoc_id'];
    $player_image = URL_IMAGES . 'noimage.jpg';
    $output = "<div align=center>$username info<BR><BR><img src=\"$player_image\"></img></div><p><BR><BR>this is the profile for this user, a full overview with all their stats and details with a pretty picture<p>";
    $options = array();
    $options["/gladiator/fight/people/$user_id/"] = 'Battle';
    $output .= player_options($options);
    return $output;
}

function select_user($user_info, $link, $pre)
{
    $username = $user_info['prefix'] . '' . $user_info['username'] . '' . $user_info['postfix'];
    $user_id = $user_info['assoc_id'];
    $output = ahref($link,$pre . $username);
    return $output;
}

} 

?>